package com.ruoyi.web.controller.module.order;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.market.domain.ConfigGlobal;
import com.ruoyi.market.domain.Level;
import com.ruoyi.market.service.IConfigGlobalService;
import com.ruoyi.market.service.IConfigOrderService;
import com.ruoyi.market.service.ILevelService;
import com.ruoyi.order.domain.OrderPk;
import com.ruoyi.order.service.IOrderPkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * PK订单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/order/pk")
public class OrderPkController extends BaseController
{
    @Autowired
    private IOrderPkService orderPkService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private IConfigGlobalService configGlobalService;

    @Autowired
    private ILevelService levelService;

    /**
     * 获取PK订单列表
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/orderPkList")
    public TableDataInfo list(@RequestBody OrderPk orderPk, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderPk.setShopId(shopId);
        }
        startPageByPost();
        List<OrderPk> list = orderPkService.selectOrderPkList(orderPk);
        return getDataTable(list);
    }

    @Log(title = "PK订单管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('order:pk:export')")
    @PostMapping("/orderPkExport")
    public void export(HttpServletResponse response, OrderPk orderPk)
    {
        List<OrderPk> list = orderPkService.selectOrderPkList(orderPk);
        ExcelUtil<OrderPk> util = new ExcelUtil<OrderPk>(OrderPk.class);
        util.exportExcel(response, list, "PK订单数据");
    }

    /**
     * 根据店员ID获取详细信息
     */
    @PostMapping("/orderPkInfoByEmployeeUserId")
    public AjaxResult orderPkInfoByEmployeeUserId(@RequestBody Map<String, Object> params)
    {
        String employeeUserId = params.get("employeeUserId").toString(); // 店员id
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(employeeUserId))
        {
            OrderPk orderPk = orderPkService.selectOrderPkByUserId(Long.parseLong(employeeUserId));
            ajax.put(AjaxResult.DATA_TAG, orderPk);
        }
        return ajax;
    }

    /**
     * 根据PK订单编号获取详细信息
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @GetMapping(value = { "/", "/{orderNo}" })
    public AjaxResult getInfo(@PathVariable(value = "orderNo", required = false) String orderNo)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(orderNo))
        {
            OrderPk orderPk = orderPkService.selectOrderPkByOrderNo(orderNo);
            ajax.put(AjaxResult.DATA_TAG, orderPk);
        }
        return ajax;
    }

    /**
     * 新增PK订单 - 店员创建
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @Log(title = "PK订单管理 - 店员创建PK订单", businessType = BusinessType.INSERT)
    @PostMapping("/orderPkCreate")
    public AjaxResult orderPkCreate(@Validated @RequestBody OrderPk orderPk, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderPk.setShopId(shopId);
        }
        Long userId = SecurityUtils.getUserId();
        EmployeeUser user = employeeUserService.selectUserById(userId);
        ConfigGlobal configGlobal = configGlobalService.selectConfigGlobalByShopId(user.getShopId());
        if(configGlobal.getPkStatus().equals(UserConstants.NO)){
            return error("创建PK失败：系统未开放PK功能");
        }
        if(user.getScoreTotal() < configGlobal.getPkScore()){
            return error("创建PK失败：评分未达到PK门槛分值");
        }
        if(orderPkService.countOrderPkByEmployeeId(userId) > 0){
            return error("创建PK失败：已有未开始或者进行中的PK订单");
        }
        if(configGlobal.getPkTime() <= 0){
            return error("创建PK失败：PK时间不能少于0");
        }
        orderPk.setShopId(shopId);
        orderPk.setPkTime(configGlobal.getPkTime());
        orderPk.setStartLevelId(user.getUserLevel());
        AjaxResult ajax = AjaxResult.success();
        ajax.put(AjaxResult.DATA_TAG, orderPkService.insertOrderPk(orderPk));
        return ajax;
    }

    /**
     * PK订单管理 - 抢单
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @Log(title = "PK订单管理 - 店员抢单PK订单", businessType = BusinessType.UPDATE)
    @PostMapping("/grabOrderPk")
    public AjaxResult grabOrderPk(@RequestBody OrderPk orderPk, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if (shopId == null || shopId.equals("")) {
            return error("店铺基本配置失败：参数错误");
        }
        OrderPk order = orderPkService.selectOrderPkByOrderNo(orderPk.getOrderNo());
        if(StringUtils.isNull(order)){
            return error("操作失败：订单不存在");
        }
        if(!order.getPkStatus().equals(UserConstants.STATUS_PREPARING)){
            return error("操作失败：该PK状态不可参与");
        }
        Long userId = SecurityUtils.getUserId();
        if(userId.equals(order.getStartUserId())){
            return error("操作失败：PK双方不能是同一个人");
        }

        if(orderPkService.countOrderPkByEmployeeId(userId) > 0){
            return error("操作失败：已有未开始或者进行中的PK订单");
        }

        EmployeeUser acceptUser = employeeUserService.selectUserById(userId);
        ConfigGlobal configGlobal = configGlobalService.selectConfigGlobalByShopId(acceptUser.getShopId());
        if(acceptUser.getUserLevel() != order.getStartLevelId()){
            if(configGlobal.getPkIsBeyond().equals(UserConstants.NO)){
                return error("操作失败：不能跨级PK");
            }
        }

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime afterAddingHours = now.plusHours(order.getPkTime());
        ZonedDateTime zonedDateTime = afterAddingHours.atZone(ZoneId.systemDefault());
        order.setPkEndTime(Date.from(zonedDateTime.toInstant()));

        Level accept_user_level = levelService.selectLevelById(acceptUser.getUserLevel());
        order.setAcceptUserThreshold(accept_user_level.getPkCommissionAmount());

        Level start_user_level = levelService.selectLevelById(order.getStartLevelId());
        order.setStartUserThreshold(start_user_level.getPkCommissionAmount());

        order.setAcceptLevelId(acceptUser.getUserLevel());
        order.setAcceptUserId(userId);
        order.setPkStatus(UserConstants.STATUS_GOING);
        order.setPkStartTime(new Date());
        orderPkService.updateOrderPk(order);

        return AjaxResult.success(order);
    }


    /**
     * PK订单管理 - 店员取消PK订单
     */
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/employeeCancelOrderPk")
    public AjaxResult employeeCancelOrderPk(@RequestBody OrderPk orderPk)
    {
        OrderPk order = orderPkService.selectOrderPkByOrderNo(orderPk.getOrderNo());
        if(StringUtils.isNull(order)){
            return error("操作失败：订单不存在");
        }
        if(!order.getPkStatus().equals(UserConstants.STATUS_PREPARING)){
            return error("操作失败：订单状态不可取消");
        }
        Long userId = SecurityUtils.getUserId();
        if(!order.getStartUserId().equals(userId)){
            return error("操作失败：无权限操作");
        }
        orderPkService.cancelOrderPk(order);
        return AjaxResult.success();
    }

    /**
     * 新增PK订单 - 后台新增
     */
    @PreAuthorize("@ss.hasPermi('order:pk:add')")
    @Log(title = "PK订单管理 - 后台新增PK订单", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@Validated @RequestBody OrderPk orderPk, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if (shopId == null || shopId.equals("")) {
            return error("操作失败：店铺参数错误");
        }

        if(orderPkService.countOrderPkByEmployeeId(orderPk.getStartUserId()) > 0){
            return error("操作失败：发起者已有未开始或者进行中的PK");
        }

        if(orderPkService.countOrderPkByEmployeeId(orderPk.getAcceptUserId()) > 0){
            return error("操作失败：接受者已有未开始或者进行中的PK");
        }

        if(orderPk.getStartUserId().equals(orderPk.getAcceptUserId())){
            return error("操作失败：PK双方不能是同一个人");
        }

        ConfigGlobal configGlobal = configGlobalService.selectConfigGlobalByShopId(shopId);
        if (configGlobal == null || configGlobal.equals("")) {
            return error("操作失败：PK配置为空");
        }
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime afterAddingHours = now.plusHours(configGlobal.getPkTime());
        ZonedDateTime zonedDateTime = afterAddingHours.atZone(ZoneId.systemDefault());
        orderPk.setPkEndTime(Date.from(zonedDateTime.toInstant()));

        EmployeeUser acceptUser = employeeUserService.selectUserById(orderPk.getAcceptUserId());
        Level accept_user_level = levelService.selectLevelById(acceptUser.getUserLevel());
        orderPk.setAcceptUserThreshold(accept_user_level.getPkCommissionAmount());

        EmployeeUser startUser = employeeUserService.selectUserById(orderPk.getStartUserId());
        Level start_user_level = levelService.selectLevelById(startUser.getUserLevel());
        orderPk.setStartUserThreshold(start_user_level.getPkCommissionAmount());

        orderPk.setStartLevelId(startUser.getUserLevel());
        orderPk.setAcceptLevelId(acceptUser.getUserLevel());
        orderPk.setPkStatus(UserConstants.STATUS_GOING);
        orderPk.setPkStartTime(new Date());
        orderPk.setPkTime(configGlobal.getPkTime());
        orderPk.setShopId(shopId);
        orderPkService.insertOrderPk(orderPk);

        return AjaxResult.success(orderPk);
    }

    /**
     * 修改PK订单
     */
    @PreAuthorize("@ss.hasPermi('order:pk:edit')")
    @Log(title = "PK订单管理 - 修改PK订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody OrderPk orderPk)
    {
        return toAjax(orderPkService.updateOrderPk(orderPk));
    }

    /**
     * 删除PK订单
     */
    @PreAuthorize("@ss.hasPermi('order:pk:remove')")
    @Log(title = "PK订单管理 - 删除PK订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderNos}")
    public AjaxResult remove(@PathVariable String[] orderNos)
    {
        return toAjax(orderPkService.deleteOrderPkByOrderNos(orderNos));
    }
}
